<template>
  <div class="app-container">
    <!-- {{ agreeRefundVisible }} -->
    <h3 class="title">已完成订单</h3>
    <div v-if="setPermissionBtn('/room/order/query/page', searchBtn)" class="inputBox">
      <el-input v-model="search.orderSn" class="input" placeholder="请输入订单号查询" />
      <el-input v-model="search.roomName" class="input" placeholder="请输入房间名称查询" />
      <el-input v-model="search.customerName" class="input" placeholder="请输入入住人查询" />
      <el-input v-model="search.customerPhone" class="input" placeholder="请输入入住人手机号查询" />
      <el-date-picker
        v-model="search.startTime"
        class="startDate"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择开始日期"/>
      <el-date-picker
        v-model="search.endTime"
        class="endDate"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择结束日期"/>
      <el-select v-model="search.orderStatus" class="input" placeholder="请选订单状态">
        <el-option :value="''" label="全部" />
        <el-option :value="310" label="已入住" />
        <el-option :value="320" label="未入住" />
        <el-option :value="330" label="未操作" />
      </el-select>
      <el-button type="primary" class="ml10" @click="toSearch">{{ searchBtn.btnName }}</el-button>
      <el-button type="primary" @click="toReset">重置</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中请稍后"
      border
      fit
      highlight-current-row>
      <template slot="empty">
        <div class="noData">暂无数据</div>
      </template>
      <el-table-column label="订单编号" width="130">
        <template slot-scope="scope">
          {{ scope.row.orderSn }}
        </template>
      </el-table-column>
      <el-table-column label="房型名称">
        <template slot-scope="scope">
          {{ scope.row.roomName }}
        </template>
      </el-table-column>
      <el-table-column label="类型">
        <template slot-scope="scope">
          {{ scope.row.roomType }}
        </template>
      </el-table-column>
      <el-table-column label="预定间夜">
        <template slot-scope="scope">
          {{ scope.row.totalNum }}
        </template>
      </el-table-column>
      <el-table-column label="总价">
        <template slot-scope="scope">
          {{ Math.ceil(scope.row.totalAmount*100)/100 }} 元
        </template>
      </el-table-column>
      <el-table-column label="预定人">
        <template slot-scope="scope">
          {{ scope.row.customerName }}
        </template>
      </el-table-column>
      <el-table-column label="预定人手机号" width="110">
        <template slot-scope="scope">
          {{ scope.row.customerPhone }}
        </template>
      </el-table-column>
      <el-table-column label="下单时间" width="100">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <!-- 已取消 -100
      * -100 无效订单(已取消订单)
      * 0    待支付
      * 100  已支付订单---待确认订单(小程序端)
      * 200  已确认订单(确认有房)---待入住订单(小程序端)
      * 210  已入住---入住中订单(小程序端)
      * 220  未入住---入住中订单(小程序端)
      * 230  未操作---入住中订单(小程序端)
      * 310  已完成订单(已入住)
      * 320  已完成订单(未入住)
      * 330  已完成订单(未操作)
      * 400  申请退款订单---退款中订单(小程序端)
      * 410  已退款订单
      * 420  拒绝退款订单 -->
      <el-table-column label="订单状态">
        <template slot-scope="scope">
          <span v-if="scope.row.orderStatus === -100">已取消</span>
          <span v-else-if="scope.row.orderStatus === 0">未付款</span>
          <span v-else-if="scope.row.orderStatus === 100">已付款</span>
          <span v-else-if="scope.row.orderStatus === 200">已确认</span>
          <span v-else-if="scope.row.orderStatus === 210">已入住</span>
          <span v-else-if="scope.row.orderStatus === 220">未入住</span>
          <span v-else-if="scope.row.orderStatus === 230">未操作</span>
          <span v-else-if="scope.row.orderStatus === 310">已完成(已入住)</span>
          <span v-else-if="scope.row.orderStatus === 320">已完成(未入住)</span>
          <span v-else-if="scope.row.orderStatus === 330">已完成(未操作)</span>
          <span v-else-if="scope.row.orderStatus === 400">申请退款</span>
          <span v-else-if="scope.row.orderStatus === 410">已退款</span>
          <span v-else-if="scope.row.orderStatus === 420">拒绝退款</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="400">
        <template slot-scope="scope">
          <el-button
            v-if="setPermissionBtn('/room/order/query/info', scope.row)"
            v-show="scope.row.orderStatus !== 400"
            size="mini"
            value="订单详情"
            type="warning"
            @click="see(scope.$index)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('/room/order/confirm', scope.row)"
            v-show="scope.row.orderStatus === 100"
            size="mini"
            value="确认有房"
            type="success"
            @click="confirmRoom(scope.row.id, scope.$index)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('/room/order/cancel', scope.row)"
            v-show="scope.row.orderStatus === 100"
            size="mini"
            value="取消"
            type="danger"
            @click="cancelRoom(scope.row.id, scope.$index)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('/room/order/refund/agree', scope.row)"
            v-show="scope.row.orderStatus === 400 && scope.row.roomRefundOrder.refundOrderStatus === 5 || scope.row.orderStatus === 400 && scope.row.roomRefundOrder.refundOrderStatus === 6"
            size="mini"
            value="完成退款"
            type="success"
            @click="finishRefund(scope.row.roomRefundOrder.id, scope.$index)">完成退款</el-button>
          <el-button
            v-if="setPermissionBtn('/room/order/refund/agree', scope.row)"
            v-show="scope.row.orderStatus === 400 && scope.row.roomRefundOrder.refundOrderStatus === 0"
            size="mini"
            value="同意退款"
            type="success"
            @click="agreeRefund(scope.row.roomRefundOrder.id, scope.$index)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('/room/order/refund/refuse', scope.row)"
            v-show="scope.row.orderStatus === 400 && scope.row.roomRefundOrder.refundOrderStatus === 0"
            size="mini"
            value="拒绝退款"
            type="danger"
            @click="refusedRefund(scope.row.roomRefundOrder.id, scope.$index)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('/room/back/order/info', scope.row)"
            v-show="scope.row.orderStatus === 410 || scope.row.orderStatus === 420"
            size="mini"
            value="退单详情"
            type="warning"
            @click="refundDetail(scope.row.roomRefundOrder.operateId, scope.$index)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('/room/order/confirm/live', scope.row)"
            v-show="scope.row.orderStatus === 200 || scope.row.orderStatus === 330"
            size="mini"
            value="确认入住"
            type="primary"
            @click="confirmCheckIn(scope.row.id, scope.row.orderStatus)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('/room/order/confirm/unlive', scope.row)"
            v-show="scope.row.orderStatus === 200 || scope.row.orderStatus === 330"
            size="mini"
            value="确认未入住"
            type="primary"
            @click="confirmNuCheckIn(scope.row.id, scope.row.orderStatus)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('remarks', scope.row)"
            v-show="scope.row.orderStatus === 0 || scope.row.orderStatus === 100 || scope.row.orderStatus === 200 || scope.row.orderStatus === 400"
            size="mini"
            value="备注"
            type="primary"
            @click="changeRemarks(scope.row.id, scope.$index)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('query/remarks', scope.row)"
            v-show="scope.row.orderStatus === 210 ||
              scope.row.orderStatus === 220 ||
              scope.row.orderStatus === 230 ||
              scope.row.orderStatus === 310 ||
              scope.row.orderStatus === 320 ||
              scope.row.orderStatus === 330 ||
              scope.row.orderStatus === 410 ||
            scope.row.orderStatus === -100"
            size="mini"
            value="查看备注"
            type="success"
            @click="checkRemark(scope.row.id, scope.$index)">{{ scope.row.btnName }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
    <remark
      v-if="remarkVisible"
      :remark-list="remarkList"
      :remark-visible.sync="remarkVisible"
      :remark-index="remarkIndex"
      :remark-type="'hotel'"/>
    <remarkPropt
      ref="remarke"
      :remark-propt-list="remarkProptList"
      :remark-propt-visible.sync="remarkProptVisible"
      :remark-propt-index="remarkProptIndex"
      :remark-type="'hotelOrder'"
      @remarkText="remarkText" />
    <detail :detialvisible.sync="dialogTableVisible" :dialogdata.sync="list" :myindex.sync="detailIndex" :detail-mode="'hotelOrder'" />
    <!-- <logistics :logistics-visible.sync="logistics" :logistics-index="logisticsIndex" :logistics-order-sn="orderSn"/> -->
    <!-- <sendGoods
      :send-goods-visible.sync="sendGoodsVisible"
      :send-goods-index="sendGoodsIndex"
      :send-goods-data="sendGoodsData"
      @shipped="shipped"/> -->
    <!-- 确认有房 -->
    <confirmOrder
      :detialvisible.sync="confirmRoomVisible"
      :dialogdata.sync="list"
      :myindex.sync="confirmRoomIndex"
      :detail-mode="'confirmRoom'"
      @confirmOrder="confirmOrderFn"/>

    <!-- 取消 -->
    <confirmOrder
      :detialvisible.sync="cancelRoomVisible"
      :dialogdata.sync="list"
      :myindex.sync="cancelRoomIndex"
      :detail-mode="'cancelRoom'"
      @cancelOrder="cancelOrderFn"/>

    <!-- 同意退款 -->
    <confirmOrder
      :detialvisible.sync="agreeRefundVisible"
      :dialogdata.sync="list"
      :myindex.sync="agreeRefundIndex"
      :detail-mode="'agreeRefund'"
      @refund="agreeRefundFn"/>

    <!-- 拒绝退款 -->
    <confirmOrder
      :detialvisible.sync="refusedRefundVisible"
      :dialogdata.sync="list"
      :myindex.sync="refusedRefundIndex"
      :detail-mode="'refusedRefund'"
      @refund="refusedRefundFn"/>

    <!-- 完成退款 -->
    <confirmOrder
      :detialvisible.sync="finishRefundVisible"
      :dialogdata.sync="list"
      :myindex.sync="finishRefundIndex"
      :detail-mode="'finishRefund'"
      @refund="finishRefundFn"/>

    <!-- 退单详情 -->
    <confirmOrder
      :detialvisible.sync="refundDetailVisible"
      :dialogdata.sync="list"
      :myindex.sync="refundDetailIndex"
      :detail-mode="'refundDetail'"/>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import detail from '@/components/detail'
import Dialog from '@/components/Dialog'
import remark from '@/components/remark'
import remarkPropt from '@/components/remark/remarkPrompt'
import logistics from '@/components/logistics'
import sendGoods from '@/components/sendGoods'
import confirmOrder from '@/components/hotel/ConfirmOrder'

import { Message } from 'element-ui'
import { getLocalUid, setLocalUid, getLocalId, setLocalId } from '@/utils/uid'
import { getPermission } from '@/api/permission'
import { getLocalUserName, setLocalUserName } from '@/utils/uid'
import { getStoreOrder, getStoreOrderRemarks } from '@/api/storeOrder'
// import { cancelExpress } from '@/api/express'

import { getRoomOrderList, confirmRoom, cancelRoom, confirmCheckInMenu, confirmCheckIn, confirmUncheckIn, getRoomRemarkList, handelRefund, agreeRefund, refuseRefund, getOperatorName } from '@/api/hotel'

export default {
  components: { Pagination, Dialog, detail, remarkPropt, remark, logistics, sendGoods, confirmOrder },
  filters: {
  },
  data() {
    return {
      searchBtn: {},
      // visible: false,
      remarkProptVisible: false,
      remarkProptList: [],
      remarkProptIndex: -1,
      userName: '',
      userType: -1,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 0,
        pageSize: 10
      },
      search: {
        orderSn: '',
        roomName: '',
        customerName: '',
        customerPhone: '',
        startTime: '',
        endTime: '',
        orderStatus: null,
        orderStatusList: '310, 320, 330'
      },
      dialogTableVisible: false,
      detailIndex: -1,
      permissionShow: false, // 权限数据未到达之前按钮隐藏
      // permissionList: [] // 权限数据列表
      remarkVisible: false,
      remarkIndex: -1,
      remarkList: [],

      // 确认有房
      confirmRoomVisible: false,
      confirmRoomIndex: -1,

      // 取消
      cancelRoomVisible: false,
      cancelRoomIndex: -1,

      // 同意退款
      agreeRefundVisible: false,
      agreeRefundIndex: -1,

      // 拒绝退款
      refusedRefundVisible: false,
      refusedRefundIndex: -1,

      // 完成退款
      finishRefundVisible: false,
      finishRefundIndex: -1,

      // 退单详情
      refundDetailVisible: false,
      refundDetailIndex: -1
    }
  },
  computed: {
    // 权限按钮 computed
    setPermissionBtn() {
      return function(str, row) {
        let index = -1
        const buttonList = this.$store.getters.button
        index = buttonList.findIndex(item => item.value === str)
        // console.log(index)
        if (index !== -1) {
          row.btnName = buttonList[index].name
          return true
        } else {
          return false
        }
      }
    }
  },
  watch: {
    'permissionList'(newVal) {
      this.permissionList = newVal
      this.permissionShow = true
    }
  },
  created() {
    // this.getUserType()
    this.fetchData()
    // console.log('userType:', this.userType)
    // this.getPermissonFn()
  },
  mounted() {
    this.getPermissonFn() // 获取按钮权限 vuex的button
  },
  methods: {
    // 确认入住
    confirmCheckIn(id, orderStatus) {
      this.$confirm('确认入住？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        confirmCheckIn({ id }).then(res => {
          if (res.code === '200') {
            Message.success('操作成功')
            this.fetchData()
          } else {
            Message.error(res.message + '-' + res.data)
            this.listLoading = false
          }
        })
      })
    },
    // 确认未入住
    confirmNuCheckIn(id, orderStatus) {
      this.$confirm('确认未入住？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        confirmUncheckIn({ id }).then(res => {
          if (res.code === '200') {
            Message.success('操作成功')
            this.fetchData()
          } else {
            Message.error(res.message + '-' + res.data)
            this.listLoading = false
          }
        })
      })
    },
    // 确认有房
    confirmRoom(id, index) {
      this.confirmRoomVisible = true
      this.confirmRoomIndex = index
    },
    // 确认有房回调
    confirmOrderFn(id) {
      console.log(id)
      this.listLoading = true
      confirmRoom({ id }).then(res => {
        if (res.code === '200') { // 已确认
          Message.success('操作成功')
          this.fetchData()
        } else {
          Message.error(res.message + '-' + res.data)
          this.listLoading = false
        }
      })
    },
    // 取消
    cancelRoom(id, index) {
      this.cancelRoomVisible = true
      this.cancelRoomIndex = index
    },
    // 取消回调
    cancelOrderFn(id) {
      console.log(id)
      this.listLoading = true
      cancelRoom({ id }).then(res => {
        if (res.code === '200') {
          Message.success('已取消')
          this.fetchData()
        } else {
          Message.error(res.message + '-' + res.data)
          this.listLoading = false
        }
      })
    },

    // 同意退款
    agreeRefund(id, index) {
      this.agreeRefundVisible = true
      this.agreeRefundIndex = index
    },
    // 同意退款回调
    agreeRefundFn(id) {
      console.log('同意退款')
      this.listLoading = true
      agreeRefund({ id }).then(res => {
        if (res.code === '200') {
          Message.success('已退款')
          this.fetchData()
        } else {
          Message.error(res.message + '-' + res.data)
          this.listLoading = false
        }
      })
    },

    // 拒绝退款
    refusedRefund(id, index) {
      this.refusedRefundVisible = true
      this.refusedRefundIndex = index
    },
    // 拒绝退款回调
    refusedRefundFn(id) {
      console.log('拒绝退款')
      this.listLoading = true
      refuseRefund({ id }).then(res => {
        if (res.code === '200') {
          Message.success('已拒绝')
          this.fetchData()
        } else {
          Message.error(res.message + '-' + res.data)
          this.listLoading = false
        }
      })
    },

    // 完成退款
    finishRefund(id, index) {
      this.finishRefundVisible = true
      this.finishRefundIndex = index
    },
    // 完成退款回调
    finishRefundFn(id) {
      console.log('完成退款')
      this.listLoading = true
      handelRefund({ id }).then(res => {
        if (res.code === '200') {
          Message.success('已手动完成退款')
          this.fetchData()
        } else {
          Message.error(res.message + '-' + res.data)
          this.listLoading = false
        }
      })
    },

    // 退单详情 refundDetail
    refundDetail(id, index) {
      this.refundDetailVisible = true
      this.refundDetailIndex = index
    },

    // 订单详情
    see(index) {
      this.dialogTableVisible = true
      this.detailIndex = index
    },
    // 查看备注
    checkRemark(id, index) {
      const obj = { roomOrderId: id }
      getRoomRemarkList(obj).then(res => {
        console.log('查看备注:', res)
        if (res.code === '200') {
          this.remarkList = res.data.list
          if (this.remarkList.length) {
            this.remarkVisible = true
            this.remarkIndex = index
          } else {
            this.$message('暂无备注');
          }
        } else {
          Message.error(res.message + '-' + res.data)
        }
      })
    },
    // 写备注
    changeRemarks(roomsId, index) {
      this.remarkProptIndex = index
      this.remarkProptVisible = true
      this.$refs.remarke.getRoomsRemark(roomsId)
    },
    remarkText() {
      this.fetchData()
    },
    getUserType() {
      switch (getLocalUserName()) {
        case 'admin':
          this.userType = 1
          break;
        case 'sale':
          this.userType = 2
          break;
        case 'casher':
          this.userType = 3
          break;
      }
    },
    // 查询
    toSearch() {
      if (this.search.startTime && this.search.endTime) {
        const start = new Date(this.search.startTime).getTime();
        const end = new Date(this.search.endTime).getTime();
        if (start > end) {
          Message.error('结束时间必须大于开始时间')
          return false
        }
      }
      if (this.search.startTime && this.search.startTime.indexOf(' 00:00:00') === -1) this.search.startTime += ' 00:00:00'
      if (this.search.endTime && this.search.endTime.indexOf(' 23:59:59') === -1) this.search.endTime += ' 23:59:59'
      if (this.search.startTime && this.search.endTime) {
        const start = new Date(this.search.startTime).getTime();
        const end = new Date(this.search.endTime).getTime();
        if (start > end) {
          Message.error('结束时间必须大于开始时间')
          return false
        }
      }
      if (this.search.startTime) this.search.startTime
      if (this.search.endTime) this.search.endTime
      this.listLoading = true
      console.log(this.search)
      const newData = this.objectCon(this.listQuery, this.search)
      console.log('this.search.orderStatus:', this.search.orderStatus)
      if (this.search.orderStatus === '' || this.search.orderStatus === null) {
        newData.orderStatusList = '310, 320, 330'
      } else {
        newData.orderStatusList = this.search.orderStatus
      }
      getRoomOrderList(newData).then(response => {
        if (response.code === '200') {
          this.list = response.data.list
          this.total = response.data.total
        } else {
          Message.error(response.message + '-' + response.data)
        }
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // 重置
    toReset() {
      this.search.orderSn = ''
      this.search.roomName = ''
      this.search.customerName = ''
      this.search.customerPhone = ''
      this.search.startTime = ''
      this.search.endTime = ''
      this.search.orderStatus = ''
    },
    /*
      <!-- 已取消 -100
      * -100 无效订单(已取消订单)
      * 0    待支付
      * 100  已支付订单---待确认订单(小程序端)
      * 200  已确认订单(确认有房)---待入住订单(小程序端)
      * 210  已入住---入住中订单(小程序端)
      * 220  未入住---入住中订单(小程序端)
      * 230  未操作---入住中订单(小程序端)
      * 310  已完成订单(已入住)
      * 320  已完成订单(未入住)
      * 330  已完成订单(未操作)
      * 400  申请退款订单---退款中订单(小程序端)
      * 410  已退款订单
      * 420  拒绝退款订单 -->
      */
    fetchData() {
      this.listLoading = true
      const newData = this.objectCon(this.listQuery, this.search)
      getRoomOrderList(this.listQuery).then(response => {
        if (response.code === '200') {
          this.list = response.data.list
          //   this.list[0].orderStatus = 100
          //   this.list[1].orderStatus = 400
          //   this.list[1].orderStatus = 310
          //   this.list[2].orderStatus = 320
          //   this.list[3].orderStatus = 330
          //   this.list[4].orderStatus = 410
          //   this.list[5].orderStatus = 420
          console.log('订单数据：', this.list)
          this.total = response.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 0.5 * 1000)
        } else {
          this.listLoading = false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .inputBox{
    div{ margin-bottom: 10px;}
    .input:nth-of-type(1){ width: 184px }
    .input:nth-of-type(2){ width: 160px }
    .input:nth-of-type(3){ width: 144px }
    .input:nth-of-type(4){ width: 186px }
    .startDate, .endDate{ width: 150px }
    .input:nth-of-type(7){width:140px}
  }
</style>
